package com.suyang.syt.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.suyang.syt.dao.interfaces.DictionaryDao;
import com.suyang.syt.model.Dictionary;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.util.EmptyUtil;

@Repository
public class DictionaryDaoImpl extends BaseDaoImpl<Dictionary> implements DictionaryDao {

	@Override
	public long countByName(String name, long pid) {
		String hql = "select count(*) from Dictionary where pid=? and name=?";
		return (Long) this.queryByHql(hql, new Object[] { pid, name });
	}

	@Override
	public PagerEasyUI<Dictionary> listByEasyUI(int page, int rows, String sort, String order, String createDate1, String createDate2) {
		StringBuilder hql = new StringBuilder("from Dictionary where 1=1 ");
		if (EmptyUtil.isNotEmpty(createDate1)) {
			hql.append(" and createTime>='").append(createDate1).append("'");
		}
		if (EmptyUtil.isNotEmpty(createDate2)) {
			hql.append(" and createTime<='").append(createDate2).append("'");
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by ").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<Dictionary> easyUIPager = new PagerEasyUI<Dictionary>();
		List<Dictionary> list = this.findByEasyUI(hql.toString(), page, rows);
		easyUIPager.setRows(list);
		easyUIPager.setTotal((Long) this.queryByHql(" select count(*)" + hql.substring(0, hql.indexOf("order by"))));
		return easyUIPager;
	}

	@Override
	public void deletes(String ids) {
		String[] idsArr = ids.split(",");
		if (idsArr != null && idsArr.length > 0) {
			Dictionary dictionary = null;
			for (String id : idsArr) {
				dictionary = this.load(Long.parseLong(id));
				if (dictionary != null && dictionary.getPid() == 0) {
					// 说明是数据字典类型,需要删除该类型下所有的字典
					String hql = " delete from Dictionary where pid=? ";
					this.executeByHql(hql, dictionary.getId());
				}
			}
		}
		String hql = " delete from Dictionary where id in(" + ids + ")";
		this.executeByHql(hql);
	}

	@Override
	public List<Dictionary> listByPid(long pid) {
		String hql = " from Dictionary where pid=? order by orderIndex desc ";
		return this.list(hql, pid);
	}

}
